package com.mmz.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/user")
public class ValidateController {
	@RequestMapping("/getCode")
	public void getCode(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setContentType("image/jpeg");// 输出的文本格式为jpg
		BufferedImage image = new BufferedImage(100, 30,
				BufferedImage.TYPE_INT_RGB);// BufferedImage他是一个类
		Graphics g = image.getGraphics();// 绘图工具
		g.setColor(Color.cyan);
		g.fillRect(0, 0, 100, 30);
		// 用来随机抽取验证码
		String[] keys = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
				"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L",
				"M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X",
				"Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
				"k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
				"w", "x", "y", "z" };
		// 验证码字体
		String[] fonts = { "新宋体", "微软雅黑" };
		// 大小
		int[] sizes = { 18, 19, 20, 21, 22, 23, 24 };
		// 字体形状
		int[] sys = { 0, Font.BOLD, Font.ITALIC, Font.BOLD + Font.ITALIC };
		String code = "";// 验证码
		// 随机获取4位验证码
		for (int i = 0; i < 4; i++) {
			String c = keys[(int) (Math.random() * keys.length)];// 从keys数组中随机抽取一位验证码
			String font = fonts[(int) (Math.random() * fonts.length)];// 随机获取字体
			int size = sizes[(int) (Math.random() * sizes.length)]; // 设置大小
			int sty = sys[(int) (Math.random() * sys.length)];
			int r1 = (int) Math.random() * 190;
			int g1 = (int) Math.random() * 190;
			int b1 = (int) Math.random() * 190;
			Color color = new Color(r1, g1, b1); // 背景颜色
			g.setFont(new Font(font, sty, size)); // 设置完整的字体
			g.setColor(color);
			g.drawString(c, 5 + (i * 24), 26); // 图片中的字体大小
			code += c; // 验证码叠加
		}
		HttpSession session = request.getSession();
		session.setAttribute("loginCode", code); // 保存验证码到session域中
		ImageIO.write(image, "jpeg", response.getOutputStream());

	}

}
